package com.qiguliuxing.dts.admin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.service.base.DtsAccountService;
import com.qiguliuxing.dts.service.base.DtsUserService;
import com.qiguliuxing.dts.service.qcode.QCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.core.support.JacksonUtil;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.domain.DtsUser;
import com.qiguliuxing.dts.db.domain.DtsUserAccount;

@RestController
@RequestMapping("/admin/user")
@Validated
@Api(tags = ApiAdminConsts.User.PARENT)
public class AdminUserController {
	private static final Logger logger = LoggerFactory.getLogger(AdminUserController.class);

	@Autowired
	private DtsUserService userService;

	@Autowired
	private QCodeService qCodeService;

	@Autowired
	private DtsAccountService accountService;

	@RequiresPermissions("admin:user:list")
	@RequiresPermissionsDesc(menu = { "用户管理", "会员管理" }, button = "查询")
	@ApiOperation(value=ApiAdminConsts.User.LIST)
	@GetMapping("/list")
	@WebLog(description = ApiAdminConsts.User.LIST,excludes = {LogParamsConsts.RESPONSE})
	public Object list(@ApiParam(value = "用户名") String username,
					   @ApiParam(value = "手机号") String mobile,
					   @ApiParam(value = "页码",defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
					   @ApiParam(value = "分页大小",defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit,
					   @ApiParam(value = "排序字段",defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
					   @ApiParam(value = "排序时间",defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {
		List<DtsUser> userList = userService.querySelective(username, mobile, page, limit, sort, order);
		long total = PageInfo.of(userList).getTotal();
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("male", userService.maleCount());
		data.put("female",userService.femaleCount());

		data.put("items", userList);
		return ResponseUtils.ok(data);
	}

	/**
	 * 订单详情
	 *
	 * @param id
	 * @return
	 */
	@RequiresPermissions("admin:user:read")
	@RequiresPermissionsDesc(menu = { "用户管理", "会员管理" }, button = "代理详情")
	@ApiOperation(value="代理详情")
	@GetMapping("/detailApprove")
	public Object detailApprove(@ApiParam(value = "用户id") @NotNull Integer id) {
		DtsUserAccount dbAccount = userService.detailApproveByUserId(id);
		if (dbAccount == null) {
			logger.error("用户管理->会员管理->代理详情 错误：userID:{},{}",id,"代理账号信息不存在");
			ResponseUtils.badArgumentValue();
		}return ResponseUtils.ok(dbAccount);
	}

	@RequiresPermissions("admin:user:approveAgency")
	@RequiresPermissionsDesc(menu = { "用户管理", "会员管理" }, button = "代理审批")
	@ApiOperation(value="代理审批")
	@PostMapping("/approveAgency")
	public Object approveAgency(@RequestBody String body) {
		Integer userId = JacksonUtil.parseInteger(body, "userId");
		Integer settlementRate = JacksonUtil.parseInteger(body, "settlementRate");
		if (userId == null || settlementRate == null || settlementRate.intValue() < 0 ){
			return ResponseUtils.badArgument();
		}
		try {
			/*
			 * 生成代理用户独有分享的二维码需要小程序已经上线，所以未上线小程序这里调用会异常
			 * 建议通过后台参数控制，因为定制用户对这里的特殊性要求，本程序暂不做调整
			 */
			String shareUrl = qCodeService.createShareUserImage(userId);

			/**
			 * 结算当前用户的订单佣金给其代理
			 * 在用户审批通过成为代理用户之前下的订单，结算佣金应归属于前一个代理用户
			 * 后续的订单由用户申请或系统自动结算给，代理用户直接会将佣金结算给自己
			 */
			boolean result = accountService.settlementPreviousAgency(userId);
			if (!result) {
				logger.warn("用户管理->会员管理->代理审批 存在异常：{}","当前用户订单佣金交割给代理用户时出错！");
			}

			userService.approveAgency(userId,settlementRate,shareUrl);
			return ResponseUtils.ok();
		} catch (Exception e) {
			logger.error("用户管理->会员管理->代理审批 出错：{}",e.getMessage());
			e.printStackTrace();
		}
		return ResponseUtils.fail();
	}
}
